<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登录/注册</title>
    <link rel="icon" th:href="@{/favicon.png}" type="image/png"/>
    <script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <link rel="stylesheet" th:href="@{/css/User.css}">
</head>
<body>
<div id="app">
<!--  &lt;!&ndash; 新增加载动画 &ndash;&gt;-->
<!--  <div class="loader">-->
<!--    <div class="loader-circle"></div>-->
<!--  </div>-->

  <!-- 顶部导航 -->
  <div class="top-nav">
    <button class="nav-btn" @click="goHome">返回主页面</button>
    <button class="nav-btn" @click="switchForm">
      {{ currentForm === 'login' ? '切换到注册' : '切换到登录' }}
    </button>
  </div>

  <!-- 登录表单 -->
  <div class="container" v-if="currentForm === 'login'">
    <div class="auth-card">
      <div class="card-header">
        <div class="logo">My Server</div>
        <div class="card-subtitle">服务器模拟经营平台</div>
      </div>

      <form class="auth-form" @submit.prevent="handleLogin">
        <div class="form-group">
          <label for="loginUsername" class="form-label">用户名</label>
          <input type="text" id="loginUsername" class="form-input"
                 v-model="loginData.username" placeholder="输入您的用户名" required>
          <div class="error-message">{{ loginErrors.username }}</div>
        </div>

        <div class="form-group">
          <label for="loginPassword" class="form-label">密码</label>
          <div class="password-container">
            <input :type="showLoginPassword ? 'text' : 'password'"
                   id="loginPassword" class="form-input"
                   v-model="loginData.password" placeholder="输入您的密码" required>
            <button type="button" class="toggle-password"
                    @click="showLoginPassword = !showLoginPassword">
              {{ showLoginPassword ? '🔒' : '👁️' }}
            </button>
          </div>
          <div class="error-message">{{ loginErrors.password }}</div>
        </div>

        <button type="submit" class="submit-btn">登录服务器</button>
      </form>

      <div class="form-footer">
        还没有账户？<a href="#" @click.prevent="currentForm = 'register'">立即注册</a>
      </div>
    </div>
  </div>

  <!-- 注册表单 -->
  <div class="container" v-if="currentForm === 'register'">
    <div class="auth-card">
      <div class="card-header">
        <div class="logo">My Server</div>
        <div class="card-subtitle">创建您的服务器管理账户</div>
      </div>

      <form class="auth-form" @submit.prevent="handleRegister">
        <div class="form-group">
          <label for="registerUsername" class="form-label">用户名</label>
          <input type="text" id="registerUsername" class="form-input"
                 v-model="registerData.username" placeholder="设置您的用户名" required>
          <div class="error-message">{{ registerErrors.username }}</div>
        </div>

        <div class="form-group">
          <label for="registerPassword" class="form-label">密码</label>
          <div class="password-container">
            <input :type="showRegisterPassword ? 'text' : 'password'"
                   id="registerPassword" class="form-input"
                   v-model="registerData.password" placeholder="设置安全密码" required>
            <button type="button" class="toggle-password"
                    @click="showRegisterPassword = !showRegisterPassword">
              {{ showRegisterPassword ? '🔒' : '👁️' }}
            </button>
          </div>
          <div class="error-message">{{ registerErrors.password }}</div>
        </div>

        <div class="form-group">
          <label for="confirmPassword" class="form-label">确认密码</label>
          <div class="password-container">
            <input :type="showConfirmPassword ? 'text' : 'password'"
                   id="confirmPassword" class="form-input"
                   v-model="registerData.confirmPassword" placeholder="再次输入密码" required>
            <button type="button" class="toggle-password"
                    @click="showConfirmPassword = !showConfirmPassword">
              {{ showConfirmPassword ? '🔒' : '👁️' }}
            </button>
          </div>
          <div class="error-message">{{ registerErrors.confirmPassword }}</div>
        </div>

        <button type="submit" class="submit-btn">创建账户</button>
      </form>

      <div class="form-footer">
        已有账户？<a href="#" @click.prevent="currentForm = 'login'">立即登录</a>
      </div>
    </div>
  </div>

  <!-- 底部版权 -->
  <div class="footer">
    Copyright &copy; 2025 Wooming Games. 版权所有。
  </div>
</div>
<script>
  const { createApp, ref, reactive } = Vue;

  createApp({
    setup() {
      // 当前显示的表单类型（login/register）
      const currentForm = ref(localStorage.getItem('userInit') ? localStorage.getItem('userInit') : 'login');

      // 登录表单数据
      const loginData = reactive({
        username: '',
        password: ''
      });

      // 登录表单错误信息
      const loginErrors = reactive({
        username: '',
        password: ''
      });

      // 注册表单数据
      const registerData = reactive({
        username: '',
        password: '',
        confirmPassword: ''
      });

      // 注册表单错误信息
      const registerErrors = reactive({
        username: '',
        password: '',
        confirmPassword: ''
      });

      // 密码可见性状态
      const showLoginPassword = ref(false);
      const showRegisterPassword = ref(false);
      const showConfirmPassword = ref(false);

      // 切换表单类型
      const switchForm = () => {
        currentForm.value = currentForm.value === 'login' ? 'register' : 'login';
      };

      // 返回主页
      const goHome = () => {
        console.log("返回主页面");
        window.location.href = '/';
      };

      // 验证登录表单
      const validateLogin = () => {
        let isValid = true;

        // 重置错误信息
        loginErrors.username = '';
        loginErrors.password = '';

        if (!loginData.username.trim()) {
          loginErrors.username = '请输入用户名';
          isValid = false;
        }

        if (!loginData.password) {
          loginErrors.password = '请输入密码';
          isValid = false;
        }

        return isValid;
      };

      // 验证注册表单
      const validateRegister = () => {
        let isValid = true;

        // 重置错误信息
        registerErrors.username = '';
        registerErrors.password = '';
        registerErrors.confirmPassword = '';

        if (!registerData.username.trim()) {
          registerErrors.username = '请输入用户名';
          isValid = false;
        }

        if (!registerData.password) {
          registerErrors.password = '请输入密码';
          isValid = false;
        }

        if (!registerData.confirmPassword) {
          registerErrors.confirmPassword = '请确认密码';
          isValid = false;
        } else if (registerData.password !== registerData.confirmPassword) {
          registerErrors.confirmPassword = '两次输入的密码不一致';
          isValid = false;
        }

        return isValid;
      };

      // 处理登录提交
      const handleLogin = async () => {
        if (!validateLogin()) return;

        try {
          // 使用 Axios 发送登录请求
          axios.post('/api/public/login', {
            username: loginData.username,
            password: loginData.password
          }).then((r) => {
            // 判断是否成功
            if (r.data.code === 200) {
              // 保存jwt
              localStorage.setItem('jwt', r.data.data);
              console.log("登录成功，跳转到主页面");
              localStorage.removeItem('userInit')
              window.location.href = '/';
            } else {
              loginErrors.password = r.data.message || '登录失败，请检查凭证';
            }
          })
        } catch (error) {
          console.error('登录请求失败:', error);
          loginErrors.password = '登录请求失败，请重试';
        }
      };

      // 处理注册提交
      const handleRegister = async () => {
        if (!validateRegister()) return;

        try {
          // 使用 Axios 发送注册请求
          const response = await axios.post('/api/public/register', {
            username: registerData.username,
            password: registerData.password
          }).then((r)  => {
            if (r.data.code === 200) {
              // 保存 jwt
              localStorage.setItem('jwt', r.data.data);
              console.log("注册成功，跳转到主页面");
              localStorage.removeItem('userInit')
              window.location.href = '/';
            }  else {
              registerErrors.username = r.data.message || '注册失败，请检查凭证';
            }
          });
        } catch (error) {
          console.error('注册请求错误:', error);
          registerErrors.username = '服务器错误，请稍后重试';
        }
      };

      return {
        currentForm,
        loginData,
        loginErrors,
        registerData,
        registerErrors,
        showLoginPassword,
        showRegisterPassword,
        showConfirmPassword,
        switchForm,
        goHome,
        handleLogin,
        handleRegister
      };
    }
  }).mount('#app');

  // // 页面加载完成后移除加载动画
  // window.addEventListener('load', function() {
  //   setTimeout(function() {
  //     document.querySelector('.loader').style.display = 'none';
  //   }, 500);
  // });
</script>
</body>
</html>